package com.example.login;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import cn.hutool.http.server.HttpServerRequest;
import com.example.msg.Result;
import com.example.pojo.Emp;
import com.example.service.EmpService;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.web.bind.annotation.*;



import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.net.HttpCookie;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {


    @Resource
    private EmpService empService;

    @PostMapping("/empLogin")
    public Result login(@RequestBody Emp emp) {
        Emp empData = empService.login(emp);
//        返回给前端jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",empData.getId());
        claims.put("username",empData.getUsername());
        claims.put("password",empData.getPassword());
        String jwt = JwtUtils.generateJwt(claims);
//        System.out.println(1/0);
        return Result.success(jwt);
    }

    @GetMapping("/c1")
    public Result setCookie(HttpServletResponse response){
        //设置cookie 返回给浏览器，浏览器会自动保存，之后再请求时 会携带这个cookie
        response.addCookie(new javax.servlet.http.Cookie("name","password"));
        return Result.success("1");
    }

    @GetMapping("/c2")
    public Result getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
           if(cookie.getName().equals("name")){
               System.out.println("name:"+cookie.getValue());
           }
        }
        return Result.success("1");
    }


    @GetMapping("/s1")
    public Result setSession(HttpSession session){
        log.info("HttpSession-s1:{}",session.hashCode());
        session.setAttribute("loginUser","tom"); //往session中存储数据
        return Result.success("1");
    }

    @GetMapping("/s2")
    public Result getSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        log.info("HttpSession-s2:{}",session.hashCode());

        Object loginUser = session.getAttribute("loginUser"); //从session中获取数据
        log.info("loginUser:{}",loginUser);
        return Result.success(loginUser);
    }

}
